from django.db import models
from django.utils.text import slugify

class Category(models.Model):
    """分类模型，同时用于文档分类和导航菜单"""
    
    title = models.CharField('标题', max_length=100)
    slug = models.SlugField('URL别名', max_length=100, unique=True)
    description = models.TextField('描述', blank=True)
    parent = models.ForeignKey('self', verbose_name='父级分类',
                              null=True, blank=True,
                              on_delete=models.CASCADE,
                              related_name='children')
    
    # 导航相关字段
    is_nav = models.BooleanField('是否显示在导航', default=False)
    nav_path = models.CharField('导航路径', max_length=200, blank=True)
    nav_icon = models.CharField('导航图标', max_length=50, blank=True)
    nav_sort = models.IntegerField('导航排序', default=0)
    
    # 通用字段
    order_index = models.IntegerField('排序', default=0)
    is_active = models.BooleanField('是否启用', default=True)
    created_at = models.DateTimeField('创建时间', auto_now_add=True)
    updated_at = models.DateTimeField('更新时间', auto_now=True)

    class Meta:
        verbose_name = '分类'
        verbose_name_plural = verbose_name
        ordering = ['order_index', 'created_at']
        
    def __str__(self):
        return self.title
        
    def save(self, *args, **kwargs):
        if not self.slug:
            self.slug = slugify(self.title)
        super().save(*args, **kwargs)
        
    def get_ancestors(self):
        """获取所有祖先分类"""
        ancestors = []
        current = self.parent
        while current:
            ancestors.append(current)
            current = current.parent
        return reversed(ancestors)
        
    def get_descendants(self):
        """获取所有子孙分类"""
        descendants = []
        for child in self.children.all():
            descendants.append(child)
            descendants.extend(child.get_descendants())
        return descendants
        
    def get_absolute_url(self):
        """获取目录的绝对URL"""
        return f'/categories/{self.slug}/' 